package com.tp.user_server.config.redis;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.*;
import redis.clients.jedis.util.Hashing;
import redis.clients.jedis.util.Sharded;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class RedisShardedPool {
    @Autowired
    private JedisConfig jedisConfig;
    private ShardedJedisPool pool;



    public JedisCluster initPool(){
        System.out.println("-------------------------------------------------------------------------------------------------");
        JedisPoolConfig config=new JedisPoolConfig();
        config.setMaxIdle(Integer.parseInt(jedisConfig.getMaxidle()));
        config.setMaxTotal(Integer.parseInt(jedisConfig.getMaxtotal()));
        config.setMinIdle(Integer.parseInt(jedisConfig.getMinidle()));

        config.setTestOnBorrow(Boolean.parseBoolean(jedisConfig.getTestborrow()));
        config.setTestOnReturn(Boolean.parseBoolean(jedisConfig.getTestreturn()));
        //whether block when resource is exhausted: false will throw a exception,true will block until timeout, default is true
        config.setBlockWhenExhausted(true);
        String[] clusters = jedisConfig.getNodes().split(",");//形成node结点的数组

//        List<JedisShardInfo> jedisShardInfos=new ArrayList<>();
        Set<HostAndPort> nodes = new HashSet<>();
        for(String cluster : clusters){
            String host = cluster.split(":")[0];//获取ip
            int port = Integer.parseInt(cluster.split(":")[1]);//获取端口
            nodes.add(new HostAndPort(host,port));

//            JedisShardInfo jedisShardInfo1=new JedisShardInfo(host,port,1000*2);
//            jedisShardInfos.add(jedisShardInfo1);
        }
        return new JedisCluster(nodes,2000,1000,1,new GenericObjectPoolConfig());
//        pool = new ShardedJedisPool(config,jedisShardInfos, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
    }

}
